package clientSide;

import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.io.UnsupportedEncodingException;
import org.eclipse.swt.SWT;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Text;

import common.Message;
import common.MessageType;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormAttachment;

public class InstanceChat extends Composite {
	private Browser browser;
	private Text text;
	private String target;
	Client client;

	public String getTarget() {
		return target;
	}

	static String SCRIPT01 = "var html = \"\";"
			+ "if (typeof window.getSelection != \"undefined\") {"
			+ "var sel = window.getSelection();" + "if (sel.rangeCount) {"
			+ "var container = document.createElement(\"div\");"
			+ "for (var i = 0, len = sel.rangeCount; i < len; ++i) {"
			+ "container.appendChild(sel.getRangeAt(i).cloneContents());" + "}"
			+ "html = container.innerHTML;" + "}"
			+ "} else if (typeof document.selection != \"undefined\") {"
			+ "if (document.selection.type == \"Text\") {"
			+ "html = document.selection.createRange().htmlText;" + "}" + "}"
			+ "return html";

	private void BuildContent() {
		StringBuilder stringbuilder = new StringBuilder();
		stringbuilder.append("<html>");
		stringbuilder.append("<head>");
		stringbuilder.append("<script>");
		stringbuilder
				.append("function AddContent(content){var theDiv = document.getElementById(\"chatId\");theDiv.innerHTML += content;}");
		stringbuilder.append("</script>");
		stringbuilder
				.append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />");
		stringbuilder.append("</head>");
		stringbuilder.append("<div id=\"chatId\">");
		stringbuilder.append("</div>");
		stringbuilder.append("</body>");
		browser.setText(stringbuilder.toString());
	}

	public void AddContent(String content) {
		browser.execute("AddContent('" + content + "')");
	}

	/**
	 * Create the composite.
	 * 
	 * @param parent
	 * @param style
	 */
	public InstanceChat(Composite parent, int style, String target,
			Client _client) {
		super(parent, style);
		setLayout(new GridLayout(1, false));
		this.target = target;
		this.client = _client;

		Composite composite_1 = new Composite(this, SWT.NONE);
		composite_1.setLayout(new FormLayout());
		GridData gd_composite_1 = new GridData(SWT.FILL, SWT.FILL, true, false,
				1, 1);
		gd_composite_1.heightHint = 38;
		composite_1.setLayoutData(gd_composite_1);

		Button btnContact = new Button(composite_1, SWT.NONE);
		btnContact.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				// call form add to contact

			}
		});
		FormData fd_btnContact = new FormData();
		btnContact.setLayoutData(fd_btnContact);
		btnContact.setText("+ Contact");

		Button btnIgnore = new Button(composite_1, SWT.NONE);
		fd_btnContact.left = new FormAttachment(btnIgnore, -83, SWT.LEFT);
		fd_btnContact.top = new FormAttachment(btnIgnore, 0, SWT.TOP);
		fd_btnContact.right = new FormAttachment(btnIgnore, -6);
		FormData fd_btnIgnore = new FormData();
		fd_btnIgnore.top = new FormAttachment(0, 5);
		fd_btnIgnore.right = new FormAttachment(100, -10);
		btnIgnore.setLayoutData(fd_btnIgnore);
		btnIgnore.setText("+ Ignore");
		browser = new Browser(this, SWT.BORDER);
		browser.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));

		Menu menu = new Menu(browser);
		browser.setMenu(menu);
		MenuItem mntmCopy = new MenuItem(menu, SWT.NONE);
		mntmCopy.setText("Copy");
		mntmCopy.addSelectionListener(new SelectionListener() {
			@Override
			public void widgetSelected(SelectionEvent arg0) {
				// TODO Auto-generated method stub
				String selection = (String) browser.evaluate(SCRIPT01);
				if (selection != null)
					Toolkit.getDefaultToolkit().getSystemClipboard()
							.setContents(new StringSelection(selection), null);
			}

			@Override
			public void widgetDefaultSelected(SelectionEvent e) {
				// TODO Auto-generated method stub
			}
		});

		Composite composite = new Composite(this, SWT.NONE);
		GridData gd_composite = new GridData(SWT.FILL, SWT.FILL, true, false,
				1, 1);
		gd_composite.heightHint = 41;
		composite.setLayoutData(gd_composite);
		GridLayout gl_composite = new GridLayout(7, true);
		gl_composite.verticalSpacing = 0;
		composite.setLayout(gl_composite);

		text = new Text(composite, SWT.BORDER);
		GridData gd_text = new GridData(SWT.FILL, SWT.FILL, true, true, 6, 1);
		gd_text.widthHint = 378;
		text.setLayoutData(gd_text);
		text.addKeyListener(new KeyListener() {
			boolean shift_press = false;

			@Override
			public void keyReleased(KeyEvent e) {
				// TODO Auto-generated method stub
				if (e.keyCode == 13 && !shift_press) {
					if (text.getText().length() == 0)
						return;
					try {
						client.SendMessage(new Message(client.getUsername(),
								getTarget(), MessageType.SendMessage, text
										.getText().getBytes("UTF-8")));
						AddContent("<b>" + client.getUsername() + "</b>: "
								+ text.getText() + "<br/>");
						text.setText("");

					} catch (Exception e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				}
			}

			@Override
			public void keyPressed(KeyEvent e) {
				// TODO Auto-generated method stub
				// if(e.keyCode == java.awt.event.KeyEvent.VK_SHIFT)
				// shift_press = true;
			}
		});

		Button btnSend = new Button(composite, SWT.NONE);
		btnSend.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				// Add message
				if (text.getText().length() == 0)
					return;
				try {
					client.SendMessage(new Message(client.getUsername(),
							getTarget(), MessageType.SendMessage, text
									.getText().getBytes("UTF-8")));
					AddContent("<b>" + client.getUsername() + "</b>: "
							+ text.getText() + "<br/>");
					text.setText("");
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		});
		btnSend.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 1,
				1));
		btnSend.setText("Send");
		new Label(composite, SWT.NONE);
		new Label(composite, SWT.NONE);
		new Label(composite, SWT.NONE);
		new Label(composite, SWT.NONE);
		new Label(composite, SWT.NONE);
		new Label(composite, SWT.NONE);
		new Label(composite, SWT.NONE);
		BuildContent();
	}

	@Override
	protected void checkSubclass() {
		// Disable the check that prevents subclassing of SWT components
	}

	public void AddMessage(final Message message) {
		Display.getDefault().asyncExec(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					AddContent("<b>" + message.getSender() + ":</b>"
							+ new String(message.getContent(), "UTF-8")
							+ "<br/>");
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
	}
}
